/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fb.model;

import business.service.MongoDbFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import com.fb.common.NewsData;
import com.fb.common.Re_News_NewsCate_Data;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import org.bson.types.ObjectId;

/**
 *
 * @author Administrator
 */
public class NewsModel {
    private static final String NEWS_COLLECTION = "news";
    private static final Logger logger = Logger.getLogger(NewsModel.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static NewsModel _instance = null;
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    
    public static NewsModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new NewsModel();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public NewsModel() {
        try {
        } catch (Exception ex) {
            logger.error("NewsModel: " + ex);
        }
    }
    
    
    public List<NewsData> getNews(int start, int limit) {
        List<NewsData> lstNews = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("created", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(NEWS_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);

            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }

            lstNews = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String objectId = ((ObjectId) dbObject.get("_id")).toString();
                String title = (String) dbObject.get("title");
                String slug = (String) dbObject.get("slug");
                String desc = (String) dbObject.get("desc");
                String content = (String) dbObject.get("content");
                long time = (long) dbObject.get("time");
                String author = (String) dbObject.get("author");
                String editor = (String) dbObject.get("editor");
                long updated = (long) dbObject.get("updated");
                long created = (long) dbObject.get("created");
                int status = (int) dbObject.get("status");
                String source = (String) dbObject.get("source"); 
                String image = (String) dbObject.get("image"); 
                NewsData newsData = new NewsData(objectId, title, slug, desc, content, author, editor, updated, created, status, time, source, image);
                lstNews.add(newsData);
            }
        } catch (Exception ex) {
            logger.error("NewsModel.getNews: " + ex.getMessage(), ex);
        }
        return lstNews;
    }
    
    
    
    public List<NewsData> getNews(int start, int limit, String userSearch, String titleSearch, 
            String statusSearch, String id_Search, String created_Se, String cate) {
        List<NewsData> lstNews = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("time", -1);
            BasicDBObject query = new BasicDBObject();
            if(!titleSearch.equals("")){
                Pattern regex = Pattern.compile(titleSearch, Pattern.CASE_INSENSITIVE); 
                query.put("title", regex);
            }           
            if(!id_Search.equals("")){
                query.append("_id", new ObjectId(id_Search));
            }            
            if(!userSearch.equals(""))
                query.append("author", userSearch);
            if(!statusSearch.equals("")){
                query.append("status", Integer.parseInt(statusSearch));
            }
             
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(NEWS_COLLECTION);
            DBCursor cursor = coll.find(query).sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }

            lstNews = new ArrayList<>();
            Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String objectId = ((ObjectId) dbObject.get("_id")).toString();
                String title = (String) dbObject.get("title");
                String slug = (String) dbObject.get("slug");
                String desc = (String) dbObject.get("desc");
                String content = (String) dbObject.get("content");
                long time = (long) dbObject.get("time");
                String author = (String) dbObject.get("author");
                String editor = (String) dbObject.get("editor");
                long updated = (long) dbObject.get("updated");
                long created = (long) dbObject.get("created");
                int status = (int) dbObject.get("status");
                String source = (String) dbObject.get("source");  
                String image = (String) dbObject.get("image"); 
                                
                NewsData newsData = new NewsData(objectId, title, slug, desc, content, author, editor, updated, created, status, time, source, image);
                
                if(!created_Se.equals("")){
                    Date dateCreated = formatter.parse(created_Se);
                    Date d = new Date(created); 
                    if(d.getDate() != dateCreated.getDate() || d.getMonth() != dateCreated.getMonth()
                            || d.getYear() != dateCreated.getYear()){
                        continue;
                    }                            
                }               
                
                boolean test = cate.equals("") ? true : false;
                List<Re_News_NewsCate_Data> listOfCurrentNews = modelRe.getItemsByNewsId(objectId);
                if(!cate.equals("")){
                    for(Re_News_NewsCate_Data item : listOfCurrentNews){ 
                        if(item.getIdNewsCate().equals(cate)){
                            test = true; 
                            break;
                        }                                
                    }
                }
                
                if(test == true)
                    lstNews.add(newsData);
            }
        } catch (Exception ex) {
            logger.error("NewsModel.getNews: " + ex.getMessage(), ex);
        }
        return lstNews;
    }
    
    
    
    public NewsData getNewsById(String id) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(NEWS_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();                
                String objectId = ((ObjectId) dbObject.get("_id")).toString();
                String title = (String) dbObject.get("title");
                String slug = (String) dbObject.get("slug");
                String desc = (String) dbObject.get("desc");
                String content = (String) dbObject.get("content");
                long time = (long) dbObject.get("time");                
                String editor = (String) dbObject.get("editor");
                String author = (String) dbObject.get("author");
                long updated = (long) dbObject.get("updated");
                long created = (long) dbObject.get("created");
                int status = (int) dbObject.get("status");
                String source = (String) dbObject.get("source"); 
                String image = (String) dbObject.get("image"); 
                NewsData newsData = new NewsData(objectId, title, slug, desc, content, 
                        author, editor, updated, created, status, time, source, image);
                return newsData;
            }
        } catch (Exception ex) {
            logger.error("NewsModel.getNewsById: " + ex.getMessage(), ex);
        }
        return null;
    }
    
    
    public String addNews(NewsData newsData) {
        String id = "";
        try {
            BasicDBObject basicDBObject = new BasicDBObject()                    
                    .append("title", newsData.getTitle())
                    .append("slug", newsData.getSlug())
                    .append("desc", newsData.getDesc())
                    .append("content", newsData.getContent())
                    .append("status", newsData.getStatus())
                    .append("time", newsData.getTime())
                    .append("editor", newsData.getAuthor())
                    .append("author", newsData.getAuthor())
                    .append("updated", System.currentTimeMillis())
                    .append("created", System.currentTimeMillis())
                    .append("source", newsData.getSource())
                    .append("image", newsData.getImage());
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(NEWS_COLLECTION);
            coll.insert(basicDBObject);
            
            ObjectId objectId = (ObjectId)basicDBObject.get( "_id" );
            id = objectId.toString();
        } catch (Exception ex) {
            logger.error("NewsModel.addNews: " + ex.getMessage(), ex);
        }
        return id;
    }
    
    
    public boolean updateNews(NewsData newsData) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject()                    
                    .append("title", newsData.getTitle())
                    .append("slug", newsData.getSlug())
                    .append("desc", newsData.getDesc())
                    .append("content", newsData.getContent())
                    .append("status", newsData.getStatus())
                    .append("time", newsData.getTime())
                    .append("editor", newsData.getEditor())
                    .append("updated", System.currentTimeMillis())
                    .append("source", newsData.getSource())
                    .append("image", newsData.getImage());
                    
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(NEWS_COLLECTION);
            
            BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
            BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(newsData.getId()));
            coll.update(searchDBQuery, updateDBObject);
            return true;
        } catch (Exception ex) {
            logger.error("NewsModel.updateNews: " + ex.getMessage());
        }
        return false;
    }
        
        
    public boolean deleteNews(String id) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(NEWS_COLLECTION);
            coll.remove(new BasicDBObject("_id", new ObjectId(id)));

            return true;
        } catch (Exception ex) {
            logger.error("NewsModel.deleteNews: " + ex.getMessage(), ex);
        }
        return false;
    }
    
    
    
    
    
}
